package org.example.springmybatisdemo.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.springmybatisdemo.entity.Dept;
import org.example.springmybatisdemo.entity.PageBean;
import org.example.springmybatisdemo.mapper.DeptMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//import com.github.pagehelper.PageHelper;
//import com.github.pagehelper.PageInfo;


import java.time.LocalDateTime;
import java.util.List;

//实现类
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;

    public List<Dept> deptlist() {
//        1. 调用mapper方法获取数据并返回
        return deptMapper.deptlist();
    }

    @Override
    public void delete(Integer id) {
        int affectedRows = deptMapper.delete(id);
        if (affectedRows == 0) { // 根据受影响的行数判断删除是否成功
            throw new RuntimeException("删除失败，ID为 " + id + " 的部门不存在");
        }
//        deptMapper.delete(id);
    }

    @Override
    public void add(Dept dept) {
//        1. 补充数据
//        dept.setId(22);
    dept.setCreateTime(LocalDateTime.now());
    dept.setUpdateTime(LocalDateTime.now());

//    2. 调用mapper方法
        deptMapper.insert(dept);
    }


    public Dept detail(Integer id) {
        return deptMapper.selectionDeptDetail(id);
    }

    public void edit(Dept dept) {
//        补充基础操作
        dept.setUpdateTime(LocalDateTime.now());
//        调用mapper
        deptMapper.update(dept);
    }

    public PageBean pagelist(Integer page, Integer pageSize) {
        Long total = deptMapper.count();

        Integer start = (page - 1) * pageSize;

        List<Dept> rows = deptMapper.pagelist(start, pageSize);

        return new PageBean(total, rows);
    }

//    @Override
    public PageBean pagePluginlist(Integer page, Integer pageSize) {

//        设置分页查
        PageHelper.startPage(page, pageSize);
//        调用 mapper查询
        List<Dept> rows = deptMapper.listpluginpage();
        Page p = (Page) rows;

        return new PageBean(p.getTotal(),p.getResult());
    }
}
